<template>
  <div class="ProductTree">
    <el-tree
      ref="$tree"
      :data="list"
      :props="option"
      node-key="id"
      show-checkbox
      @check-change="handleCheckChange"
    />
  </div>
</template>

<script>
import { menuGet } from '@/api/admin/product'

export default {
  name: 'ProductTree',

  props: {
    list: {
      type: Array,
      default: () => []
    },
    id: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      // 配置
      option: {
        label: 'label',
        children: 'children'
      },

      SelectIds: []
    }
  },

  created() {
    this.init()
  },

  methods: {
    // 获取当前选中状态
    init() {
      menuGet(this.id).then(res => {
        if (res.data.code === 0) this.$refs.$tree.setCheckedKeys(res.data.data)
      })
    },

    // 选中时触发
    handleCheckChange(data) {
      const chooseList = this.$refs.$tree.getCheckedNodes()
      let saveList = []

      if (chooseList.length > 0) {
        chooseList.forEach(item => {
          saveList.push(item.id)
        })
        saveList = [...new Set(saveList)]
      } else saveList = []

      this.SelectIds = saveList
    }
  }
}
</script>

<style lang='less'>
.ProductTree{

}
</style>